package com.hj.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.hj.security.cache.TokenStoreCache;
import com.hj.security.user.HjUserDetails;
import jakarta.annotation.Resource;
import org.apache.ibatis.reflection.MetaObject;

import java.time.Instant;

/**
 * @author hj
 * @Date 2023/4/26
 * @Description: 自动填充字段
 */
public class FieldMetaObjectHandler implements MetaObjectHandler {

    @Resource
    private TokenStoreCache tokenStoreCache;

    private final static String CREATE_TIME = "createTime";

    private final static String CREATOR = "creator";

    private final static String UPDATE_TIME = "updateTime";

    private final static String UPDATER = "updater";

    private final static String VERSION = "version";

    private final static String DELETED = "deleted";

    @Override
    public void insertFill(MetaObject metaObject) {
        HjUserDetails user = tokenStoreCache.getUser();
        Instant date = Instant.now();
        // 创建者
        strictInsertFill(metaObject, CREATOR, Long.class, user.getId());
        // 创建时间
        strictInsertFill(metaObject, CREATE_TIME, Instant.class, date);
        // 更新者
        strictInsertFill(metaObject, UPDATER, Long.class, user.getId());
        // 更新时间
        strictInsertFill(metaObject, UPDATE_TIME, Instant.class, date);
        // 版本号
        strictInsertFill(metaObject, VERSION, Integer.class, 0);
        // 删除标识
        strictInsertFill(metaObject, DELETED, Integer.class, 0);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 更新者
        strictUpdateFill(metaObject, UPDATER, Long.class, tokenStoreCache.getUserId());
        // 更新时间
        strictUpdateFill(metaObject, UPDATE_TIME, Instant.class, Instant.now());
    }


}